<?php

if (!defined('BASEPATH'))
  exit('No direct script access allowed');

class Login extends MY_Controller {

  function __construct() {
    parent::__construct();

    $this->load->model('login_model', 'login');
    if ($this->session->userdata('sess_user_id')) {
      redirect('main');
    }
    $this->layout = 'front';
  }

  function index() {
    $this->load->view('login');
  }

  function auth() {
    $data = array();
    $data['username'] = $this->input->post('username');
    $data['password'] = $this->input->post('password');
    
    $this->form_validation->set_rules('username', 'username', 'trim|required|xss_clean');
    $this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean');

    if ($this->form_validation->run() == FALSE)
    {
      $this->load->view('login');
    } else {
      $result = $this->login->auth($this->input->post('username'), $this->input->post('password'));
      if (count($result) > 0 && trim($data['username']) != '' && trim($data['password']) != '' && $data['username'] == $result[0]->username && $data['password'] == $result[0]->password)
      {
        $session_data = array(
                            'sess_user_id' => $result[0]->id,
                            'sess_username' => $result[0]->username,
                            'sess_full_name' => $result[0]->full_name,
							'sess_user_type' => $result[0]->user_type
                        );
						
		// native session 
		session_start();
		$_SESSION['sup_id'] = $result[0]->id;
		$_SESSION['sup_name'] = $result[0]->username;
						
        $this->session->set_userdata($session_data);
		
		$this->load->library("user_agent");
		
		$ip=$this->input->ip_address();
 		if(!$this->input->valid_ip($ip))
		{
			$ip='Invalid ip address';
		}
 		if ($this->agent->is_browser())
		{
			$browser = $this->agent->browser().' '.$this->agent->version();
		}
		elseif ($this->agent->is_robot())
		{
			$browser = $this->agent->robot();
		}
		elseif ($this->agent->is_mobile())
		{
			$browser = $this->agent->mobile();
		}
		else
		{
			$browser = 'Unidentified User Agent';
		}
		userLog($ip,$browser);	
		
		
        redirect(base_url_2() . 'realtime');
		
		
      } else {
        $data['error'] = "Username or Password is invalid.";
        $this->layout = 'front';
        $this->load->view('login', $data);
      }
    }
  }

}

/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */